package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserLoginServiceImpl implements ApUserLoginService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDTO dto) {
        //1. 如果手机号和密码不为空  用账户密码登录
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if (StringUtils.isNotBlank(phone)&&StringUtils.isNotBlank(password)){
            //1.1根据手机号查询用户
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (apUser==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }

            //1.2判断输入的密码和用户密码是否一直
            String digest = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!digest.equals(apUser.getPassword())){
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

            }
            //1.3检测用户状态

            //1.4颁发token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));

            //1.5返回结果  data{token:  "", user:""}
            Map map = new HashMap<>();
            map.put("token",token);
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            //2 如果手机号或者密码为空 使用设备id登录
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名 密码 和 设备ID全部为空" );
            }
            //2.1检查设备id


            //2.2直接办法token 用户id 存为0
            String token = AppJwtUtil.getToken(Long.valueOf(0));
            //2.3返回结果: data{token:""}
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            return ResponseResult.okResult(map);
        }

    }
}
